<template>
	<view>
		<u--input 
			v-model="val"
			:disabled="disabled || !writable" 
			:placeholder="placeholder" 
			border="bottom" 
			:password="password"
			@change="inputChange" 
		></u--input>
		<view v-show="(required || dataTypeCheck || patternCheck) && validator" class="requiredMessage">{{ validateMessage }}</view>
	</view>
</template>

<script>
import { isValidInput } from '../utils'
export default {
	data() {
		return {
			val: '',
			validator: false,
			validateMessage: ''
		};
	},
	props: {
		value: {
			type: String,
			default: ''
		},
		placeholder: {
			type: String,
			default: '请输入内容'
		},
		disabled: {
			type: Boolean,
			default: false
		},
		writable: {
			type: Boolean,
			default: true
		},
		password: {
			type: Boolean,
			default: false
		},
		// 校验
		required: {
			type: Boolean,
			default: false
		},
		requiredMessage: {
			type: String,
			default: '值不能为空'
		},
		dataType: {
			type: String,
			default: 'string'
		},
		dataTypeCheck: {
			type: Boolean,
			default: false
		},
		dataTypeMessage: {
			type: String,
			default: '字符串错误'
		},
		pattern: {
			type: String,
			default: ''
		},
		patternCheck: {
			type: Boolean,
			default: false
		},
		patternMessage: {
			type: String,
			default: '正则匹配错误'
		}
	},
	computed: {
		validateStatus() {
			return this.$store?.state?.validate?.status || false
		}
	},
	watch: {
		value: {
			handler () {
				this.val = this.value || ''
			},
			immediate: true,
			deep: true
		},
		validateStatus() {
			if(this.validateStatus) {
				let { validator, validateMessage } = isValidInput({
					required: this.required,
					requiredMessage: this.requiredMessage,
					dataType: this.dataType,
					dataTypeCheck: this.dataTypeCheck,
					dataTypeMessage: this.dataTypeMessage,
					pattern: this.pattern,
					patternCheck: this.patternCheck,
					patternMessage: this.patternMessage,
					value: this.val
				})
				this.validator = validator
				this.validateMessage = validateMessage
			}
		},
		val() {
			if(this.validateStatus) {
				let { validator, validateMessage } = isValidInput({
					required: this.required,
					requiredMessage: this.requiredMessage,
					dataType: this.dataType,
					dataTypeCheck: this.dataTypeCheck,
					dataTypeMessage: this.dataTypeMessage,
					pattern: this.pattern,
					patternCheck: this.patternCheck,
					patternMessage: this.patternMessage,
					value: this.val
				})
				this.validator = validator
				this.validateMessage = validateMessage
			}
		}
	},
	methods: {
		inputChange(e) {
			this.$emit('input', e)
		}
	}
}
</script>

<style scoped>
.requiredMessage {
	width: 100%;
	height: 50rpx;
	line-height: 50rpx;
	color: #f56c6c;
	font-size: 22rpx;
}
</style>